package lyh.hnu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import lyh.hnu.common.R;
import lyh.hnu.dto.DishDto;
import lyh.hnu.entity.po.Dish;
import lyh.hnu.entity.po.DishFlavor;
import lyh.hnu.mapper.DishMapper;
import lyh.hnu.service.DishFlavorService;
import lyh.hnu.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;


    @Override
    @Transactional//操作多张表需要开始事务
    public void saveWithFlavor(DishDto dishDto) {
        save(dishDto);
        Long dishId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map(item -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public R<DishDto> selectByIdWithFlavor(long id) {
        DishDto dishDto = new DishDto();
        Dish dish = getById(id);
        BeanUtils.copyProperties(dish, dishDto);
        List<DishFlavor> flavorList = dishFlavorService.lambdaQuery().eq(DishFlavor::getDishId, id).list();
        dishDto.setFlavors(flavorList);
        return R.success(dishDto);
    }

    @Transactional
    @Override
    public R<String> updateWithFlavor(DishDto dishDto) {
        updateById(dishDto);
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map(item -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
        return R.success("修改菜品成功");
    }
}
